<template>
    <div>
      <el-card>
        <div slot="header" class="tabletitle">
          <span>信息化项目进度</span>
  
          <el-radio-group v-model="zoomtype" @change="zoom" style="float: right">
            <el-radio-button label="4">年</el-radio-button>
            <el-radio-button label="3">季</el-radio-button>
            <el-radio-button label="2">月</el-radio-button>
            <el-radio-button label="1">周</el-radio-button>
            <el-radio-button label="0">日</el-radio-button>
          </el-radio-group>
  
          <el-button-group
            style="float: right; margin-right: 30px; margin-top: 3px"
          >
            <el-button
              @click="showaddproject"
              type="success"
              icon="el-icon-collection"
              size="medium"
              >新增
            </el-button>
            <el-button
              @click="deleteproject"
              type="warning"
              icon="el-icon-magic-stick"
              size="medium"
              >刷新
            </el-button>
          </el-button-group>
        </div>
        <div style="height: 600px" ref="gantt"></div>
      </el-card>
  
      <el-drawer
        title="项目操作台"
        :visible.sync="showbox"
        direction="rtl"
        size="40%"
      >
        <el-main style="margin-top: -20px">
          <el-card>
            <div slot="header" class="clearfix">
              <span>项目信息卡</span>
  
              <el-button-group style="float: right; margin-bottom: 10px">
                <el-button
                  @click="addsonproject"
                  type="success"
                  size="mini"
                  icon="el-icon-collection"
                  >新增子项目
                </el-button>
  
                <el-button
                  @click="deleteproject"
                  type="danger"
                  size="mini"
                  icon="el-icon-magic-stick"
                  >删除该项目
                </el-button>
              </el-button-group>
            </div>
  
            <el-form ref="form" :model="form" label-width="80px">
              <el-form-item label="项目内容">
                <el-input v-model="form.text"></el-input>
              </el-form-item>
  
              <el-form-item label="项目说明">
                <el-input type="textarea" v-model="form.bz"></el-input>
              </el-form-item>
  
              <el-form-item label="项目日期">
                <el-date-picker
                  type="date"
                  placeholder="开始事件"
                  v-model="form.start_date"
                  style="width: 100%"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
  
              <el-form-item label="持续日期"
                ><el-input-number
                  size="medium"
                  v-model="form.duration"
                  :min="1"
                ></el-input-number
              ></el-form-item>
  
              <el-form-item label="选择颜色">
                <el-color-picker v-model="form.color"></el-color-picker>
              </el-form-item>
  
              <el-form-item label="项目进度">
                <el-slider
                  v-model="form.progress"
                  show-input
                  :min="0"
                  :max="1"
                  :step="0.01"
                  :format-tooltip="formatTooltip"
                >
                </el-slider>
              </el-form-item>
  
              <el-form-item label="负责人员" v-show="!changeuser"
                ><el-input
                  v-model="form.user"
                  :disabled="true"
                  style="width: 70%"
                ></el-input>
                <el-button
                  style="width: 30%"
                  type="primary"
                  @click="changeuser = true"
                  >变更人员</el-button
                >
              </el-form-item>
  
              <el-form-item label="负责人员" v-show="changeuser">
                <remote-select-user ref="rsu" :rsustyles="rsustyles">
                  <el-button
                    style="width: 30%"
                    type="primary"
                    @click="changeuser = true"
                    >变更人员</el-button
                  ></remote-select-user
                >
              </el-form-item>
  
              <el-form-item>
                <el-button type="primary" @click="updateproject"
                  >更新项目</el-button
                >
                <el-button>取消</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-main>
      </el-drawer>
  
      <el-dialog title="新建项目" :visible.sync="showadd">
        <el-form ref="newform" :model="newform" label-width="80px">
          <el-form-item label="项目内容">
            <el-input v-model="newform.text"></el-input>
          </el-form-item>
  
          <el-form-item label="项目说明">
            <el-input type="textarea" v-model="newform.bz"></el-input>
          </el-form-item>
  
          <el-form-item label="项目日期">
            <el-date-picker
              type="date"
              placeholder="开始时间"
              v-model="newform.start_date"
              style="width: 100%"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
  
          <el-form-item label="持续日期"
            ><el-input-number
              size="medium"
              v-model="newform.duration"
              :min="1"
            ></el-input-number
          ></el-form-item>
  
          <el-form-item label="选择颜色">
            <el-color-picker v-model="newform.color"></el-color-picker>
          </el-form-item>
  
          <el-form-item label="项目进度">
            <el-slider
              v-model="newform.progress"
              show-input
              :min="0"
              :max="1"
              :step="0.01"
              :format-tooltip="formatTooltip"
            >
            </el-slider>
          </el-form-item>
  
          <el-form-item label="负责人员">
            <remote-select-user ref="nrsu" :rsustyles="newrsustyles">
            </remote-select-user>
          </el-form-item>
  
          <el-form-item>
            <el-button type="primary" @click="addproject">新建项目</el-button>
            <el-button>取消</el-button>
          </el-form-item>
        </el-form>
        <!-- <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogFormVisible = false"
            >确 定</el-button
          >
        </div> -->
      </el-dialog>
    </div>
  </template>
  
  
  <script>
  import "dhtmlx-gantt";
  // import "dhtmlx-gantt/codebase/skins/dhtmlxgantt_meadow.css"
  
  import moment from "moment";
  import { gantt } from "dhtmlx-gantt";
  import RemoteSelectUser from "../common/RemoteSelectUser.vue";
  export default {
    components: { RemoteSelectUser },
    name: "gantt",
    data() {
      return {
        changeuser: false,
        rsustyles: {
          width: "100%",
        },
        newrsustyles: {
          width: "100%",
        },
        showadd: false,
        showbox: false,
        showedit: false,
        zoomtype: 2,
        form: {},
        newform: {},
        tasks: {
          data: [],
          links: [],
        },
        lists: [
          {
            icon: "mdi-account",
            text: "个人中心",
            src: "/user/info",
          },
        ],
      };
    },
    created() {
      this.getprojectlist();
    },
  
    methods: {
      formatTooltip(val) {
        return Math.trunc(val * 100) + "%";
      },
  
      getmarker() {
        var dateToStr = gantt.date.date_to_str(gantt.config.task_date);
  
        var markerId = gantt.addMarker({
          start_date: new Date(),
          css: "today",
          text: "今天",
          title: dateToStr(new Date()),
        });
  
        gantt.getMarker(markerId);
      },
  
      showaddproject() {
        this.newform = {};
        this.showadd = true;
        this.newform.parent = 0;
        this.newform.row_height = 50;
        this.newform.bar_height = 45;
      },
  
      addsonproject() {
        this.newform = {};
        this.showadd = true;
        this.newform.parent = this.form.id;
        this.newform.row_height = 40;
        this.newform.bar_height = 35;
      },
  
      updateproject(id) {
        gantt.clearAll();
        let datas = {};
        if (this.showbox) {
          datas = {
            form: this.form,
            postid: sessionStorage.getItem("id"),
            userid: this.$refs.rsu.userid,
          };
        } else {
          for (let index = 0; index < this.tasks.data.length; index++) {
            if (this.tasks.data[index].id == id) {
              datas = {
                form: this.tasks.data[index],
                postid: sessionStorage.getItem("id"),
                userid: [],
              };
            }
          }
        }
  
        this.$axios
          .post("api/project/updateproject", datas)
          .then((response) => {
            for (let index = 0; index < this.tasks.data.length; index++) {
              if (this.tasks.data[index].id == this.form.id) {
                this.tasks.data[index] = this.form;
              }
            }
          
            gantt.parse(this.tasks);
            this.getmarker();
  
            this.showbox = false;
            this.$notify({
              title: "更新成功",
              message: response.data,
              type: "success",
              duration: 1500,
            });
          })
          .catch(function (error) {
            console.log(error);
          });
      },
  
      addlink(id, item) {
        let datas = {
          id: id,
          source: item.source,
          target: item.target,
          type: item.type,
        };
  
        this.$axios
          .post("api/project/addlink", datas)
          .then((response) => {
            this.$notify({
              title: "添加成功",
              message: response.data.messages,
              type: "success",
              duration: 1500,
            });
          })
          .catch(function (error) {
            console.log(error);
          });
      },
  
      deletelink(id, item) {
        console.log(id);
        let datas = {
          id: id,
        };
  
        this.$axios
          .post("api/project/deletelink", datas)
          .then((response) => {
            this.$notify({
              title: "删除成功",
              message: response.data.messages,
              type: "success",
              duration: 1500,
            });
          })
          .catch(function (error) {
            console.log(error);
          });
      },
  
      addproject() {
        gantt.clearAll();
  
        let datas = {
          form: this.newform,
          postid: sessionStorage.getItem("id"),
          userid: this.$refs.nrsu.userid,
        };
  
        this.$axios
          .post("api/project/addproject", datas)
          .then((response) => {
            this.newform.id = response.data.id;
            this.tasks.data.push(this.newform);
            gantt.parse(this.tasks);
            this.getmarker();
            this.showadd = false;
            this.showbox = false;
            this.$notify({
              title: "新建成功",
              message: response.data.messages,
              type: "success",
              duration: 1500,
            });
          })
          .catch(function (error) {
            console.log(error);
          });
      },
  
      deleteproject() {
        gantt.clearAll();
  
        for (let index = 0; index < this.tasks.data.length; index++) {
          if (this.tasks.data[index].id == this.form.id) {
            let datas = {
              id: this.form.id,
            };
  
            this.$axios
              .post("api/project/deleteproject", datas)
              .then((response) => {
                this.tasks.data.splice(index, 1);
  
                gantt.parse(this.tasks);
  
                this.getmarker();
  
                this.showbox = false;
                this.$notify({
                  title: "删除成功",
                  message: response.data.messages,
                  type: "success",
                  duration: 1500,
                });
              })
              .catch(function (error) {
                console.log(error);
              });
          }
        }
      },
  
      showinfobox(id) {
        for (let index = 0; index < this.tasks.data.length; index++) {
          if (this.tasks.data[index].id == id) {
            this.form = this.tasks.data[index];
            console.log(this.tasks.data[index]);
            this.showbox = true;
          }
        }
      },
  
      zoom(val) {
        gantt.ext.zoom.setLevel(val);
      },
  
  
  
      getprojectlist() {
        const loading = this.$loading({
          lock: true,
          text: "正在准备数据",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        if (sessionStorage.getItem("id") != null) {
          gantt.clearAll();
          let datas = {
            id: sessionStorage.getItem("id"),
          };
          this.$axios
            .post("api/project/getproject", datas)
            .then((response) => {
              this.tasks = response.data;
              console.log(response.data);
              // this.todayMaker();
              gantt.parse(this.tasks);
            })
            .catch(function (error) {
              console.log(error);
            });
  
          loading.close();
  
          return;
        } else {
          setTimeout(() => {
            this.getprojectlist();
          }, 100);
        }
      },
    },
  
    mounted: function () {
      gantt.config.columns = [
        {
          name: "text",
          label: "项目内容",
          tree: true,
          width: "*",
          align: "left",
          resize: true,
        },
        {
          name: "start_date",
          label: "启动时间",
          resize: true,
          align: "center",
          min_width: 100,
        },
        // {
        //   name: "end_date",
        //   label: "结束时间",
        //   resize: true,
        //   align: "center",
        //   min_width: 100,
        // },
        // {
        //   name: "SpeedProgress",
        //   label: "进度",
        //   resize: true,
        //   min_width: 100,
        //   align: "center",
        //   template: function (task) {
        //     return Math.round(task.progress * 100) + "%";
        //   },
        // },
        // { name: "add", width: 44 },
      ];
  
      gantt.config.date_format = "%Y-%m-%d";
  
      const zoomConfig = {
        levels: [
          {
            name: "days",
            scales: [
              { unit: "week", step: 1, format: "%Y年%M(第%W周)" },
              { unit: "day", step: 1, format: "%j日" },
            ],
            round_dnd_dates: true,
            min_column_width: 60,
            scale_height: 60,
          },
          {
            name: "weeks",
            scales: [
              { unit: "month", step: 1, format: "%M" },
              { unit: "week", step: 1, format: "第%W周" },
            ],
            round_dnd_dates: false,
            min_column_width: 60,
            scale_height: 60,
          },
          {
            name: "months",
            scales: [
              { unit: "year", step: 1, format: "%Y年" },
              { unit: "month", step: 1, format: "%M" },
            ],
            round_dnd_dates: false,
            min_column_width: 50,
            scale_height: 60,
          },
  
          {
            name: "quarter",
            scales: [
              { unit: "year", step: 1, format: "%Y年" },
              {
                unit: "quarter",
                step: 1,
                format: function quarterLabel(date) {
                  const month = date.getMonth();
                  let q_num;
                  if (month >= 9) {
                    q_num = 4;
                  } else if (month >= 6) {
                    q_num = 3;
                  } else if (month >= 3) {
                    q_num = 2;
                  } else {
                    q_num = 1;
                  }
                  return "第" + q_num + "季度";
                },
              },
            ],
            round_dnd_dates: false,
            min_column_width: 50,
            scale_height: 60,
          },
  
          {
            name: "years",
            scales: [
              { unit: "year", step: 1, format: "%Y年" },
              {
                unit: "year",
                step: 5,
                format: function (date) {
                  const dateToStr = gantt.date.date_to_str("%Y年");
                  const endDate = gantt.date.add(
                    gantt.date.add(date, 5, "year"),
                    -1,
                    "day"
                  );
                  return dateToStr(date) + " - " + dateToStr(endDate);
                },
              },
            ],
            round_dnd_dates: false,
            min_column_width: 50,
            scale_height: 60,
          },
        ],
      };
  
      //
      gantt.ext.zoom.init(zoomConfig);
      // 设置初始化甘特图时等级为1
      gantt.ext.zoom.setLevel(2);
  
      //设置时间刻度的高度和网格的标题
      gantt.config.scale_height = 60;
  
      //下面日期的宽度，会随时间长短宽度变化。但是设置最小宽度后，当时间跨度到达一定长度，就会展示最小宽度
      gantt.config.min_column_width = 50;
  
      // 甘特图行高度
      gantt.config.row_height = 40;
  
      // 甘特图条高度
      gantt.config.bar_height = 30;
  
      //使用中文
      gantt.i18n.setLocale("cn");
  
      //开启提示：鼠标悬浮在gantt行上显示
      // gantt.plugins({
      //   tooltip: true,
      // });
      gantt.plugins({
        marker: true,
      });
  
      this.getmarker();
  
      // 跳过节假日：比如你选择的包含周六日，他会自动延长时间或者缩短，延长或者缩短是因为包含节假日，要增加或者减少天数。
      gantt.config.work_time = true;
  
      gantt.config.correct_work_time = true;
  
      gantt.config.inherit_scale_class = true;
  
      gantt.templates.task_text = function (start, end, task) {
        // return "<b>任务:</b> " + task.text + ",<b> 执行人:</b> " + task.user;
        return Math.trunc(task.progress * 100) + "%";
      };
  
      gantt.locale = {
        date: {
          month_full: [
            "1",
            "2",
            "3",
            "4",
            "5",
            "6",
            "7",
            "8",
            "9",
            "10",
            "11",
            "12",
          ],
          month_short: [
            "1月",
            "2月",
            "3月",
            "4月",
            "5月",
            "6月",
            "7月",
            "8月",
            "9月",
            "10月",
            "11月",
            "12月",
          ],
          day_full: [
            "星期日",
            "星期一",
            "星期二",
            "星期三",
            "星期四",
            "星期五",
            "星期六",
          ],
          day_short: ["日", "一", "二", "三", "四", "五", "六"],
        },
        labels: {
          dhx_cal_today_button: "今天",
          day_tab: "日",
          week_tab: "周",
          month_tab: "月",
          new_event: "新建日程",
          icon_save: "保存",
          icon_cancel: "关闭",
          icon_details: "详细",
          icon_edit: "编辑",
          icon_delete: "删除",
          confirm_closing: "请确认是否撤销修改!", //Your changes will be lost, are your sure?
          confirm_deleting: "是否删除计划?",
          section_description: "描述:",
          section_time: "时间范围:",
          section_type: "类型",
          section_text: "计划名称:",
          section_color: "颜色:",
  
          /* grid columns */
  
          column_text: "计划名称",
          column_start_date: "开始时间",
          column_duration: "持续时间",
          column_add: "",
  
          /* link confirmation */
  
          link: "关联",
          confirm_link_deleting: "将被删除",
          link_start: " (开始)",
          link_end: " (结束)",
          message_ok: "确认",
          message_cancel: "取消",
  
          type_task: "任务",
          type_project: "项目",
          type_milestone: "里程碑",
  
          minutes: "分钟",
          hours: "小时",
          days: "天",
          weeks: "周",
          months: "月",
          years: "年",
        },
      };
  
      //禁用双击事件
      gantt.config.details_on_dblclick = true;
  
      // gantt.config.resize_rows = true;
  
      //关闭所有错误提示信息：gantt有自己的异常消息，如果不关闭可能页面会弹出异常消息
      gantt.config.show_errors = false;
  
      gantt.init(this.$refs.gantt);
      // 初始化
      gantt.parse(this.tasks);
  
      let that = this;
  
      //添加关联后触发
      gantt.attachEvent("onAfterLinkAdd", function (id, item) {
        that.addlink(id, item);
      });
  
      //删除关联后触发
      gantt.attachEvent("onAfterLinkDelete", function (id, item) {
        that.deletelink(id, item);
      });
  
      //添加关联后触发
      gantt.attachEvent("onAfterTaskAdd", function (id, item) {
        console.log("添加后触发");
        that.updateproject(id, item);
      });
  
      //修改任务后触发
      gantt.attachEvent("onAfterTaskUpdate", function (id, item) {
        console.log("修改任务后触发");
        that.updateproject(id);
      });
  
      // //移动任务后触发
      // gantt.attachEvent("onAfterTaskMove", function (id, parent, tindex) {
      //   console.log("移动任务后触发");
      //   that.updateproject(id);
      // });
  
      //移动进度后触发
      // gantt.attachEvent("onAfterTaskDrag", function (id, mode, e) {
      //   console.log("移动进度后触发");
      //   that.updateproject(id);
      // });
  
      // //删除任务后触发
      // gantt.attachEvent("onAfterTaskDelete", function (id, item) {
      //   console.log("删除任务后触发");
      //   that.updateproject(id);
      // });
  
      //灯箱事件
      gantt.attachEvent("onBeforeLightbox", function (id) {
        that.showinfobox(id);
      });
    },
  };
  </script>
  
   <style>
  @import "~dhtmlx-gantt/codebase/dhtmlxgantt.css";
  
  .tabletitle {
    max-height: 30px;
    font-size: 25px;
    color: #409eff;
  }
  
  .gantt_grid {
    width: 200px;
  }
  
  .gantt_grid_scale .gantt_grid_head_cell {
    background-color: #1d8ce0;
    color: rgb(255, 255, 255);
    font-size: 16px;
    /* border-bottom: 1px solid #ffffff; */
    border: 1px solid #ffffff;
  }
  
  .gantt_task .gantt_task_scale .gantt_scale_cell {
    background-color: #409eff;
    color: rgb(255, 255, 255);
    font-size: 12px;
    border-bottom: 1px solid #ffffff;
  }
  .gantt_tree_content,
  .gantt_tree_icon {
    font-family: "微软雅黑";
    height: 100%;
    display: inline-block;
  }
  .gantt_grid_head_cell {
    font-family: "微软雅黑";
    font-size: 14px;
  }
  
  /* // 引入甘特图的css文件 */
  </style>
  